package com.yy.tech.data.mapper.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.std.MapProperty;
import com.yy.tech.data.coder.encode.Encoder;
import com.yy.tech.data.context.DesensitizeContext;
import com.yy.tech.data.provider.model.FindCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yy
 * @date 2022/4/8
 * @description: TODO
 */
@Component
public class DesensitizePropertyFilter extends SimpleBeanPropertyFilter {

    @Autowired
    private DesensitizeContext context;
    @Override
    protected boolean include(final PropertyWriter writer) {
        String name = writer.getName();
        if (context.exclude(FindCondition.create(name))){
            return false;
        }
        return super.include(writer);
    }

    @Override
    protected boolean include(final BeanPropertyWriter writer) {
        String name = writer.getName();
        if (context.exclude(FindCondition.create(name))){
            return false;
        }
        return super.include(writer);
    }

    @Override
    public void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception {
        String name = writer.getName();
        if (writer instanceof MapProperty){
            Encoder encoder = context.findEncoderByRule(FindCondition.create(name));
            if (null != encoder){
                ((MapProperty) writer).setValue(encoder.encode(((MapProperty) writer).getValue()));
            }
        }
        super.serializeAsField(pojo, jgen, provider, writer);
    }
}
